<template>
  <div class="finance-page">
    <h2>财务统计</h2>

    <!-- 日期选择 -->
    <div class="date-selector">
      <el-radio-group v-model="dateRange" @change="handleDateRangeChange">
        <el-radio-button label="week">最近一周</el-radio-button>
        <el-radio-button label="month">最近一月</el-radio-button>
        <el-radio-button label="custom">自定义</el-radio-button>
      </el-radio-group>
      
      <el-date-picker
        v-if="dateRange === 'custom'"
        v-model="customDates"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        @change="loadFinance"
        style="margin-left: 20px"
      />
    </div>

    <!-- 财务概览 -->
    <div v-loading="loading" class="overview-section">
      <h3>财务概览</h3>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="overview-card revenue">
            <div class="card-icon">
              <el-icon :size="36"><Money /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-value">¥{{ finance.overview?.totalRevenue || 0 }}</div>
              <div class="card-label">总收入</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card cost">
            <div class="card-icon">
              <el-icon :size="36"><Wallet /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-value">¥{{ finance.overview?.totalCost || 0 }}</div>
              <div class="card-label">总成本</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card profit">
            <div class="card-icon">
              <el-icon :size="36"><TrendCharts /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-value">¥{{ finance.overview?.totalProfit || 0 }}</div>
              <div class="card-label">总利润</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card margin">
            <div class="card-icon">
              <el-icon :size="36"><DataLine /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-value">{{ finance.overview?.profitMargin || 0 }}%</div>
              <div class="card-label">利润率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card refund">
            <div class="card-icon">
              <el-icon :size="36"><RefreshLeft /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-value">¥{{ finance.overview?.refundAmount || 0 }}</div>
              <div class="card-label">退款金额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card net-revenue">
            <div class="card-icon">
              <el-icon :size="36"><Coin /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-value">¥{{ finance.overview?.netRevenue || 0 }}</div>
              <div class="card-label">净收入</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 收入趋势图 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>收入趋势分析</span>
            </div>
          </template>
          <div id="incomeTrendChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>

      <!-- 支出分析 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>支出分析</span>
            </div>
          </template>
          <div id="expenseChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getFinanceStats } from '@/api/dashboard'
import * as echarts from 'echarts'

const loading = ref(false)
const dateRange = ref('month')
const customDates = ref([])
const finance = reactive({
  overview: null,
  incomeTrend: [],
  expenseAnalysis: null
})

let incomeTrendChart = null
let expenseChart = null

// 加载财务数据
const loadFinance = async () => {
  loading.value = true
  try {
    let params = {}
    
    if (dateRange.value === 'custom' && customDates.value && customDates.value.length === 2) {
      params = {
        startDate: customDates.value[0],
        endDate: customDates.value[1]
      }
    } else if (dateRange.value === 'week') {
      const now = new Date()
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
      params = {
        startDate: weekAgo.toISOString().split('T')[0],
        endDate: now.toISOString().split('T')[0]
      }
    } else if (dateRange.value === 'month') {
      const now = new Date()
      const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
      params = {
        startDate: monthAgo.toISOString().split('T')[0],
        endDate: now.toISOString().split('T')[0]
      }
    }
    
    const res = await getFinanceStats(params)
    if (res.code === 200) {
      Object.assign(finance, res.data)
      
      // 渲染图表
      await nextTick()
      if (finance.incomeTrend && finance.incomeTrend.length > 0) {
        renderIncomeTrendChart()
      }
      if (finance.expenseAnalysis) {
        renderExpenseChart()
      }
    } else {
      ElMessage.error(res.message || '加载财务数据失败')
    }
  } catch (error) {
    console.error('加载财务数据失败', error)
    ElMessage.error('加载财务数据失败')
  } finally {
    loading.value = false
  }
}

// 日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value !== 'custom') {
    customDates.value = []
    loadFinance()
  }
}

// 渲染收入趋势图
const renderIncomeTrendChart = () => {
  const chartDom = document.getElementById('incomeTrendChart')
  if (!chartDom) return
  
  if (incomeTrendChart) {
    incomeTrendChart.dispose()
  }
  
  incomeTrendChart = echarts.init(chartDom)
  
  const dates = finance.incomeTrend.map(item => item.date)
  const revenueData = finance.incomeTrend.map(item => item.revenue || 0)
  const costData = finance.incomeTrend.map(item => item.cost || 0)
  const profitData = finance.incomeTrend.map(item => item.profit || 0)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['收入', '成本', '利润']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '金额（元）'
    },
    series: [
      {
        name: '收入',
        type: 'line',
        data: revenueData,
        smooth: true,
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '成本',
        type: 'line',
        data: costData,
        smooth: true,
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '利润',
        type: 'line',
        data: profitData,
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        itemStyle: {
          color: '#409eff'
        }
      }
    ]
  }
  
  incomeTrendChart.setOption(option)
  
  window.addEventListener('resize', () => {
    incomeTrendChart && incomeTrendChart.resize()
  })
}

// 渲染支出分析图
const renderExpenseChart = () => {
  const chartDom = document.getElementById('expenseChart')
  if (!chartDom) return
  
  if (expenseChart) {
    expenseChart.dispose()
  }
  
  expenseChart = echarts.init(chartDom)
  
  const data = [
    { value: finance.expenseAnalysis.productCost || 0, name: '商品成本' },
    { value: finance.expenseAnalysis.refundCost || 0, name: '退款成本' },
    { value: finance.expenseAnalysis.otherExpenses || 0, name: '其他支出' }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '支出分析',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          formatter: '{b}: ¥{c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: data,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ],
    color: ['#f56c6c', '#e6a23c', '#909399']
  }
  
  expenseChart.setOption(option)
  
  window.addEventListener('resize', () => {
    expenseChart && expenseChart.resize()
  })
}

onMounted(() => {
  loadFinance()
})
</script>

<style scoped lang="scss">
.finance-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }

  h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #666;
    font-weight: 500;
  }

  .date-selector {
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
  }

  .overview-section {
    margin-bottom: 20px;

    .overview-card {
      cursor: default;
      transition: transform 0.2s;

      &:hover {
        transform: translateY(-4px);
      }

      :deep(.el-card__body) {
        display: flex;
        align-items: center;
        padding: 20px 15px;
      }

      .card-icon {
        margin-right: 15px;
        opacity: 0.8;
      }

      .card-content {
        flex: 1;
        min-width: 0;

        .card-value {
          font-size: 20px;
          font-weight: bold;
          margin-bottom: 6px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .card-label {
          font-size: 12px;
          color: #909399;
        }
      }

      &.revenue {
        .card-icon {
          color: #67c23a;
        }
        .card-value {
          color: #67c23a;
        }
      }

      &.cost {
        .card-icon {
          color: #f56c6c;
        }
        .card-value {
          color: #f56c6c;
        }
      }

      &.profit {
        .card-icon {
          color: #409eff;
        }
        .card-value {
          color: #409eff;
        }
      }

      &.margin {
        .card-icon {
          color: #e6a23c;
        }
        .card-value {
          color: #e6a23c;
        }
      }

      &.refund {
        .card-icon {
          color: #909399;
        }
        .card-value {
          color: #909399;
        }
      }

      &.net-revenue {
        .card-icon {
          color: #5470c6;
        }
        .card-value {
          color: #5470c6;
        }
      }
    }
  }

  .charts-section {
    .card-header {
      font-size: 16px;
      font-weight: bold;
    }
  }
}
</style>
